package sz.com.postoffice.jxyzwgcase.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.fastjson.JSON;
import com.sun.istack.NotNull;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sz.com.postoffice.jxyzwgcase.constants.Constants;
import sz.com.postoffice.jxyzwgcase.core.TableDataInfo;
import sz.com.postoffice.jxyzwgcase.pojo.PersonnelSectionInformation;
import sz.com.postoffice.jxyzwgcase.service.PersonnelSectionService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName PersonnelSectionController
 * @Deacription TODO
 * @Author 王盟
 * @Date 2020/9/28 13:06
 * @Version 1.0
 **/
@Api(value = "段道与营业部揽投员关系维护", tags = "{员工信息API}")
@RestController
@Slf4j
@RequestMapping(value = "/department")
public class PersonnelSectionController {

    @Resource
    private PersonnelSectionService personnelSectionService;

    /*
    ** 
     * @description: 人员及段道信息（营业部填报） 新增
     * @param:  * @param information 
     * @return  boolean
     * @author wangmeng
     * @date: 2020/9/28 13:46
     */
    @ApiOperation(value = "新增段道与营业部员工信息", notes = "新增段道与营业部员工信息")
    @RequestMapping(value = "/persons", method = RequestMethod.POST)
    public boolean insert(@RequestBody PersonnelSectionInformation information) {
        System.out.println("开始新增...");
        return personnelSectionService.insert(information);
    }
    /*
    ** 
     * @description: 人员及段道信息（营业部填报） update
     * @param:  * @param information
     * @return  boolean
     * @author wangmeng
     * @date: 2020/9/28 13:46
     */
    @ApiOperation(value = "更新段道与营业部员工信息", notes = "更新段道与营业部员工信息")
    @RequestMapping(value = "/persons", method = RequestMethod.PUT)
    public boolean update(@RequestBody PersonnelSectionInformation information) {
        System.out.println("开始更新...");
        return personnelSectionService.update(information);
    }

    /*
    **
     * @description: 人员及段道信息（营业部填报） delete
     * @param:  * @param information
     * @return  boolean
     * @author wangmeng
     * @date: 2020/9/28 13:46
     */
    @ApiOperation(value = "删除段道与营业部员工信息", notes = "删除段道与营业部员工信息")
    @RequestMapping(value = "/persons/{pid}", method = RequestMethod.DELETE)
    public boolean delete(@PathVariable("pid") @NotNull @ApiParam(name="人员及段道id",value="path传入",required=true) Integer pid)  {
        System.out.println("开始删除...");
        return personnelSectionService.deleteByPrimaryKey(pid);
    }

   /*
   **
    * @description: 人员及段道信息（营业部填报）查询
    * @param:  * @param information
    * @return  sz.com.postoffice.jxpostoffice.core.TableDataInfo
    * @author wangmeng
    * @date: 2020/9/28 13:48
    */
    @ApiOperation(value = "查询段道与营业部员工信息", notes = "查询段道与营业部员工信息")
    @RequestMapping(value = "/persons", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", dataType = "int", paramType = "path", required = true),
            @ApiImplicitParam(name = "pageNum", value = "当前页", dataType = "int", paramType = "path", required = true)
    })
    public TableDataInfo findByInformation(PersonnelSectionInformation information) {
        System.out.println("开始查询...");
        return personnelSectionService.findByListEntity(information);
    }
    
    /*
    ** 
     * @description: 人员及段道信息（营业部填报）信息导入
     * @param:  * @param file
     * @return  java.lang.String
     * @author wangmeng
     * @date: 2020/9/28 14:28
     */
    @ApiOperation(value = "人员及段道信息（营业部填报）导入", notes = "人员及段道信息Excel")
    @PostMapping("importExcel")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
//        EasyExcel.read(file.getInputStream(), PersonnelSectionInformation.class, new PersonnelSectionListener(uploadDAO)).sheet().doRead();
        String message = personnelSectionService.upload(file);
        return message;
    }
    @RequestMapping(value = "/exportExcel", method = RequestMethod.GET)
    @ApiOperation(value = "段道与营业部员工信息导出", notes = "段道与营业部员工信息Excel导出")
    public void export(HttpServletResponse response) throws IOException {
        String fileName="段道与营业部员工信息.xlsx";

        List<PersonnelSectionInformation> allList = personnelSectionService.findAll();
        fileName = URLEncoder.encode(fileName, Constants.UTF8);
        response.addHeader("Content-Disposition", "filename=" + fileName);
        OutputStream outputStream = response.getOutputStream();
        EasyExcel.write(outputStream, PersonnelSectionInformation.class).sheet("段道与营业部员工信息").doWrite(allList);

        outputStream.close();
    }

    @ApiOperation(value = "查找单个段道与营业部员工信息", notes = "查找单个段道与营业部员工信息")
    @RequestMapping(value = "/findperByid/{pid}", method = RequestMethod.GET)
    public PersonnelSectionInformation findperByid(@PathVariable("pid") @NotNull @ApiParam(name="人员及段道id",value="path传入",required=true) Integer pid)  {
        System.out.println("开始删除...");
        return personnelSectionService.findByPrimaryKey(pid);
    }
    @ApiOperation(value = "段道与营业部员工信息 excel模板下载", notes = "段道与营业部员工信息excel模板下载")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(HttpServletResponse response) throws IOException {
        ExcelWriter write=null;
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("段道与营业部员工信息excel", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            /*EasyExcel.write(response.getOutputStream(), PersonnelSectionInformation.class).autoCloseStream(Boolean.FALSE).sheet(0,"人员及段道信息（营业部填报）")
                    .doWrite(new ArrayList());
            EasyExcel.write(response.getOutputStream(), ImportantClientInfomation.class).autoCloseStream(Boolean.FALSE).sheet(1,"重点市场及客户信息（营业部填报）")
                    .doWrite(new ArrayList());*/

            write= EasyExcel.write(response.getOutputStream()).build();
            WriteSheet writeSheet = EasyExcel.writerSheet(0, "段道与营业部员工信息").head(PersonnelSectionInformation.class).build();
            write.write(new ArrayList(), writeSheet);


        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }finally {
            // 千万别忘记finish 会帮忙关闭流
            if (write != null) {
                write.finish();
            }
        }
    }
}
